package com.mcxx.modules.base.service.read;

import com.mcxx.util.CommonUtil;
import com.yinhai.ta404.component.org.orguser.area.entity.TaAreaPo;
import com.yinhai.ta404.component.org.orguser.area.service.read.AreaManagementReadService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.*;


@Component
public class AreaHelper {
    @Autowired
    private AreaManagementReadService areaManagementReadService;

    private final static Map<String,AreaPo> AREA_CACHE = new HashMap<>();


    public AreaPo getAreaByCode(String areaCode) {
        if(CommonUtil.invalidArgs(areaCode)){
            return new AreaPo();
        }

        Assert.notNull(areaCode, "areaCode must not be null");


        AreaPo areaPo = AREA_CACHE.get(areaCode);

        if (areaPo != null) {
            return areaPo;
        }

        areaPo = getByAreaCode(areaCode);


        AREA_CACHE.put(areaCode,areaPo);

        return areaPo;
    }


    public AreaPo getAreaWithoutCache(String areaCode) {
        Assert.notNull(areaCode, "areaCode must not be null");
        return getByAreaCode(areaCode);
    }

    private AreaPo getByAreaCode(String areaCode) {
        Assert.notNull(areaCode, "areaCode must not be null");
        TaAreaPo taAreaPo = areaManagementReadService.queryAreaByAreaCode(areaCode);
        AreaPo areaPo = new AreaPo();
        if (taAreaPo == null) {
            return areaPo;
        }


        String[] temp = taAreaPo.getNamePath().split("/");
        List<String> areaNames = new ArrayList<>(Arrays.asList(temp));
        while (areaNames.size() != 5) {
            areaNames.add("");
        }

        BeanUtils.copyProperties(taAreaPo,areaPo);
        areaPo.setProvince(areaNames.get(0));
        areaPo.setCity(areaNames.get(1));
        areaPo.setCounty(areaNames.get(2));
        areaPo.setStreet(areaNames.get(3));
        areaPo.setCommunity(areaNames.get(4));

        return areaPo;
    }

    @Data
    @EqualsAndHashCode(callSuper = true)
    public static class AreaPo extends TaAreaPo{

        private String province;

        private String city;

        private String county;

        private String street;

        private String community;
    }
}
